ASP.NET WebAPI适用于构建HTTP服务的框架,可以从任何客户端(包括浏览器和移动设备)访问它。
它是在.NET Framework上构建RESTful应用程序的理想平台。
ASP.NET Web API初识
- Web API:是一种使用HTTP协议访问的Web上的API(Application programing Interface),可以使用不同的技术(如Java、.NET等)构建Web API。
- ASP.NET Web API是一个可扩展的框架,用于构建基于HTTP的服务,可以在不同平台上访问,如Web、Window。
- 工作方法与ASP.NET MVC Web Application类似,只不过它返回的是数据,而不是视图。
- 它与Web Service和WCF类型,只不过它只能使用HTTP协议。
ASP.NET Web API特性
- ASP.NET Web API构造在ASP.NET之上,支持ASP.NET请求/响应通道
- ASP.NET Web API将HTTP谓词映射到方法名称
- ASP.NET Web API支持不同格式的响应数据,内置支持JSON、XML、BSON格式
- ASP.NET Web API可以托管在IIS、自托管或支持.NET 4.0+的其他Web服务器
- ASP.NET Web API使用最新的HttpClient与Web API Server通信
ASP.NET Web API版本
Web API Version | Supported .NET Framewok | Coincides with | Supported in |
---|---|---|---|
Web API 1.0 | .NET Framework 4.0 | ASP.NET MVC 4 | VS2010 |
Web API 2 | .NET Framework 4.5 | ASP.NET MVC 5 | VS2012 、VS2013 |
ASP.NET Web API与WCF
Web API | WCF |
---|---|
开源并运行.NET框架 | 运行.NET框架 |
仅支持HTTP协议 | 支持HTTP、TCP、UDP和自定义协议 |
将HTTP谓词映射到方法 | 使用基于属性的编程模型 |
使用类似ASP.NET MVC路由和控制器概念 | 使用服务、操作、数据契约 |
不支持可靠的消息传递和事务 | 支持可靠的消息传递和事务 |
使用HttpConfiguration类配置Web API,不能在Web.config中配置 | 使用Web.config和属性配置服务 |
非常适合构建RestFul服务 | 支持构建RestFul服务,但有限制 |
选择Web API
- 使用.NET Framework 4.0或者更高版本
- 构建仅支持HTTP协议的服务
- 构建基于RestFul HTTP服务
- 熟悉ASP.NET MVC
选择WCF
- 使用.NET Framework 3.5
- 服务需要支持多种协议
- 使用WS-*标准构建服务
- 使用Request-Reply、One Way和Duplex message exchange
ASP.NET Web API创建
Web API With MVC Project
ASP.NET Web Application==>Web API
- New Project–>ASP.NET Web Application–>Web API
自动生成配置App_Start:WebApiConfig.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20//配置访问路由
namespace MyWepAPIWithMVC
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}自动生成WebApi类:ValuesController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34//继承ApiController抽象类
//默认方法映射Http谓词,如Get,Post,Put,Delete等
namespace MyWepAPIWithMVC.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}自动注册:Global.asax
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15namespace MyWepAPIWithMVC
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//启动配置WepAPI
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
Stand-alone Web API Projcet
ASP.NET Web Application==>Empty
New Project–>ASP.NET Web Application–>Empty
手动配置
安装WebAPI类库:
Micresoft ASP.NET Web API 2.2
添加Configuration文件夹,创建配置类
添加应用程序类Global.asax,启动配置
手动创建WebAPI类
ASP.NET Web API测试
Fiddler
Postman
ASP.NET Web API配置
Web API支持基于代码的配置,无法在配置文件如,Web.config中配置。
启动配置
GlobalConfiguration.Configure(WebApiConfig.Register);
路由配置
WebApiConfigure.Register(config)->config.Routes
ASP.NET Web API路由
Convention-based Routing(基于约定)
- 使用路由模板决定执行哪个Controller和Action。
- 路由表里面至少添加一个路由模板
1 | //多种路由,会按照先后顺序匹配 |
Attribute Routing(基于属性)
- 使用路由属性[Route(“xxx”)]定义路由,可以配置Controller或Action上
- 使用路由属性必须启用:config.MapHttpAttributeRoutes();
1 | [Route("api/MyWebAPI/MyGet")] |
ASP.NET Web API参数
primitive type(原始类型)
参数值来源于:query string
complex type(复杂类型)
参数值来源于:request body
参数默认绑定规则
HTTP Method | Query String | Request Body |
---|---|---|
GET | Primitive Type,Complex Type | NA |
POST | Primitive Type | Complex Type |
PUT | Primitive Type | Complex Type |
PATCH | Primitive Type | Complext Type |
DELETE | Primitive Type,Complex Type | NA |
- GET请求
参数顺序和大小写无关,名称要相同
1 | //WebAPI |
- POST请求
1 | public class StudentController : ApiController |
参数默认规则修改
[FormUri]
1
2
3
4
5
6
7
8public class StudentController : ApiController
{
public Student Post([FromUri]Student stud)
{
}
}
//Web API从请求字符串(Query String)中解析参数,而不是请求体(Request Body)[FormBody]
1
2
3
4
5
6
7
8public class StudentController : ApiController
{
public Student Post([FromBody]string name)
{
}
}
//Web API从请求体(Request Body)中解析参数,而不是请求字符串(Query String)
ASP.NET Web API返回类型
- Void
- Primitive type or Complex type
- HttpResponseMessage
- IHttpActionResult
Web API Controller
Web API 控制器是一个类,名称必须以Controller结尾,且从System.Web.Http.ApiController派生。所有公共方法都称为操作方法。
默认操作方法,与HTTP谓词匹配
GET / POST / PUT / PATCH / DELETE
方法名与HTTP谓词相同,或者以谓词开头
HTTP Method | Possible Action Name | Usage |
---|---|---|
GET | Get() any name starting with Get | Retrieves data. |
POST | Post() any name starting with Post | Inserts new record. |
PUT | Put() any name starting with Put | Updates existing record. |
PATCH | Patch() any name starting with Patch | Updates record partially. |
DELETE | Delete() any name starting with Delete | Deletes record. |
自定义方法名,使用HTTP谓词属性
HttpGet,HttpPost,HttpPut,HttpDelete等
1
2
3
4
5[HttpGet]
public string Value(int id)
{
return "value";
}
ASP.NET Web API 过滤器
Web API 过滤器用于在执行操作方法之前或者之后添加额外逻辑。如日志记录、异常处理、性能测量、身份验证和授权。
过滤器实际上是应用在Web API Controller或者action上的属性。每一个Filter必须实现System.Web.Http.Filters.IFilter接口。
重要的Filter接口:
Filter Type | Interfacce | Class | Description |
---|---|---|---|
Simple Filter | IFilter | - | Defines the methods that are used in a filter |
Action Filter | IActionFilter | ActionFilterAttribute | Used to add extra logic before or after action methods execute |
Authentication Filter | IAuthenticationFilter | - | Used to force users or clients to be authenticated before action methods execute |
Authorization Filter | IAuthorizationFilter | AuthorizationFilterAttribute | Used to restrict access to action methods to specific users or groups |
Exception Filter | IExceptionFilter | ExceptionFilterAttribute | Used to handle all unhandled exception in Web API |
Override Filter | IOverrideFilter | - | Used to customize the behavior of othe filter for individual action method |
接口:需要自己实现,抽象类:需要自己重写。
1 | //LogAttribute继承抽象类ActionFilterAttribute |
1 | //Log2Attribute继承Attribute抽象类,并实现IActionFilter接口 |
1 | namespace MyWebAPIWithNone.Controller |
ASP.NET Web API 通信
WebClient
.NET 2.0 使用WebClient与Web Server通信
HttpClient
.NET 4.5 使用HttpClient与Web Server通信
HttpClient方法
详见:HttpClient.aspx)
Method Name | Descirption |
---|---|
GetAsync | Sends a GET request to the specified Uri as an asynchronous operation |
GetByteArrayAsync | Sends a GET request to the specified Uri and returns the response body as a byte array in an asynchronous operation |
GetStreamAsync | Sends a GET request to the specified Uri and returns the response body as a stream in an asynchronous operation |
GetStringAsync | Sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation |
PostAsync | Sends a POST request to the specified Uri as an asynchronous operation |
PostAsJsonAsync | Sends a POST request as an asynchronous operation to the specified Uri with given value serialized as JSON |
PostAsXmlAsync | Sends a POST request as an asynchronous operation to the specified Uri with given value serialized as XML |
PutAsync | Sends a PUT request to the specified Uri as an asynchronous operation |
PutAsJsonAsync | Sends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as JSON |
PutAsXmlAsync | Sends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as XML |
DeletelAsync | Sends a DELETE request to the specified Uri as an asynchronous operation |
1 | //例如获取学生信息 |
ASP.NET Web API Hosting
IIS Hosting
Self Hosting
最后更新: 2018年09月16日 15:24
原始链接: https://www.github.com/ChangHub/BlogImages/raw/master/2018/09/08/ASP.NET MVC WebAPI/